import type { Context } from 'koa';
import { validate } from 'class-validator';
import type { DtoClass, NormalObj } from '@/typings/global';

export async function vailParams<T = any>(Dto: DtoClass, params: NormalObj = {}) {
  const dtoParams = new Dto();
  const keys = Object.keys(dtoParams);
  keys.forEach(key => (dtoParams[key] = params[key]));

  const result = await validate(dtoParams);

  const errors = result.reduce((prev, cur) => {
    const stacts = cur.constraints || {};
    return [...prev, ...Object.values(stacts)];
  }, [] as string[]);

  if (errors.length) {
    throw {
      vailError: true,
      message: errors.join(',')
    }
  }

  return dtoParams as T;
}